#!/usr/bin/env python

from os3.dbm.dbmanager import DBManager
from config import cfg
import urllib, sys, os

sys.path.append ( "../" )

from media_manager_class import MediaManagerHandler

dbm = DBManager ( DBManager.DBM_TYPE_MYSQL )

dbm.connect ( user = cfg.get ( "login", "root" ), 
	      passwd =  cfg.get ( "password", "" ),
	      db = cfg.get ( "db_name", "bluray" ) )


#dbm.table_truncate ( "media_data" )

def import_youtube ( dbm ):
	mm = MediaManagerHandler ( dbm )
	mm.path = cfg.get ( "dest_path" )

	cur = dbm.select ( [ "bluray_movie_link AS l", "product AS p" ],
			   [ "p.code", "l.url", "l.descr" ],
			   "p.extra_info = l.movie_code" )

	for row in cur:
		mm.add_youtube ( row [ 'code' ], row [ 'descr' ], row [ 'url' ] )

	cur.close ()

def import_images ( dbm ):
	mm = MediaManagerHandler ( dbm )
	mm.path = cfg.get ( "dest_path" )

	def _try_copy ( row, fname, descr ):
		fname_full = os.path.join ( os.path.join ( cfg.get ( "path" ), "img", fname ) )
		if not os.path.isfile ( fname_full ):
			print "Manca: %s" % fname_full
			return

		mm.add_image ( row [ 'code' ], descr, fname_full )
		

	cur = dbm.select ( "product", [ "code", "extra_info" ] )
	for row in cur:
		_try_copy ( row, row [ 'code' ] + "-1.jpg", "Blu-ray - Copertina frontale" )
		_try_copy ( row, row [ 'code' ] + "-2.jpg", "Blu-ray - Retro di copertina" )
		_try_copy ( row, row [ 'extra_info' ] + ".jpg", "Blu-ray - Immagine" )
		
	cur.close ()



#import_youtube ( dbm )
import_images ( dbm )

dbm.close ()
